package com.turbo.cloud.core.trace;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

import java.util.Map;
import java.util.Objects;

/**
 * trace 日志信息转换
 *
 * @author yangbing
 */
public class TraceConverter extends ClassicConverter {

    @Override
    public String convert(ILoggingEvent le) {
        final Map<String, String> mdcPropertyMap = le.getMDCPropertyMap();
        String clientId = "clientId";
        String traceId = "traceId";
        String currentUser = "currentUser";
        if (Objects.nonNull(mdcPropertyMap)) {
            final String tmpClientId = mdcPropertyMap.get("clientId");
            if (Objects.nonNull(tmpClientId)) {
                clientId = tmpClientId;
            }
            final String tmpTraceId = mdcPropertyMap.get("traceId");
            if (Objects.nonNull(tmpTraceId)) {
                traceId = tmpTraceId;
            }
            final String tmpCurrentUser = mdcPropertyMap.get("currentUser");
            if (Objects.nonNull(tmpCurrentUser)) {
                currentUser = tmpCurrentUser;
            }
        }
        return String.format("[%s,%s,%s,%s]", TraceThreadLocal.HOST_ID, clientId, traceId, currentUser);
    }
}
